#cron: 0 7,12,20 * * *
import requests
import os
from bs4 import BeautifulSoup
import notify2
import wxpusher
import base64

#更新链接
cpolor_cookie = os.environ.get("cpolor_cookie")
token = cpolor_cookie.split('&')[0]
cookie = cpolor_cookie.split('&')[1]
def gengxin(): 
    headers = {
    'content-length':'115',
    'cache-control':'max-age=0',
    'sec-ch-ua':'"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
    'sec-ch-ua-mobile':'?0',
    'sec-ch-ua-platform':'"Windows"',
    'upgrade-insecure-requests':'1',
    'origin':'https://dashboard.cpolar.com',
    'content-type':'application/x-www-form-urlencoded',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36',
    'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'sec-fetch-site':'same-origin',
    'sec-fetch-mode':'navigate',
    'sec-fetch-user':'?1',
    'sec-fetch-dest':'document',
    'referer':'https://dashboard.cpolar.com/login',
    'accept-encoding':'gzip, deflate, br',
    'accept-language':'zh-CN,zh;q=0.9',
    'cookie':cookie
            }
    payload=base64.b64decode(token)

    response0 = requests.request("POST", "https://dashboard.cpolar.com/login", headers=headers, data=payload)


gengxin()

headers = {
    "Host": "dashboard.cpolar.com",
    "Connection": "keep-alive",
    "sec-ch-ua": "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Google Chrome\";v=\"122\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-User": "?1",
    "Sec-Fetch-Dest": "document",
    "Referer": "https://dashboard.cpolar.com/status",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cookie": cookie
}
url = 'https://dashboard.cpolar.com/status'
html = requests.get(url = url,headers = headers)
html_content = html.text
print(html_content)
# 使用BeautifulSoup解析HTML内容，这里使用'lxml'解析器，你也可以换成'html.parser'
soup = BeautifulSoup(html_content, 'lxml')

tbody = soup.find('tbody')
result = ""  # 初始化一个空字符串，用于存储最终要打印的内容
if tbody:
    rows = tbody.find_all('tr')
    for row in rows:
        cols = row.find_all(['td', 'th'])
        if len(cols) >= 3:  # 适当放宽条件，确保能处理大部分合理情况
            tunnel_name = cols[0].text
            http_url = cols[1].text if len(cols) > 1 else ""
            region = cols[2].text if len(cols) > 2 else ""
            local_address = cols[3].text if len(cols) > 3 else ""
            create_time = cols[4].text if len(cols) > 4 else ""
            # 将各部分信息组合成一个字符串，添加到result中，每个隧道信息之间用换行和分割线隔开
            result += f"隧道名称: {tunnel_name}\n"
            result += f"URL（HTTP）: {http_url}\n"
            result += f"地区: {region}\n"
            result += f"本地地址: {local_address}\n"
            result += f"创建时间: {create_time}\n"
            result += "-" * 20 + "\n"

from bs4 import BeautifulSoup

# 原始HTML内容，用xxx代替
#html_content = "xxx"

# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html_content, 'html.parser')

# 提取.span9内容
#span9_content = soup.find(class_="span9").prettify()
# 提取.span9内容
span9 = soup.find(class_="span9")

# 检查是否存在tbody标签
tbody = span9.find('tbody') if span9 else None
if tbody:
    rows = tbody.find_all('tr')
    new_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线隧道摘要</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #fafafa;
            color: #333;
        }
        .container {
            max-width: 100%;
            width: 90%;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        h2 {
            text-align: center;
            color: #4A90E2;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            border: 1px solid #ddd;
        }
        th {
            background-color: #4A90E2;
            color: white;
            text-transform: uppercase;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        a {
            color: #4A90E2;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        @media (max-width: 600px) {
            body {
                padding: 10px;
            }
            .container {
                width: 100%;
                padding: 10px;
            }
            table, thead, tbody, th, td, tr {
                display: block;
            }
            thead tr {
                position: absolute;
                top: -9999px;
                left: -9999px;
            }
            tr {
                margin: 0 0 1rem 0;
            }
            td {
                border: none;
                position: relative;
                padding-left: 50%;
                text-align: right;
            }
            td:before {
                content: attr(data-label);
                position: absolute;
                left: 10px;
                font-weight: bold;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>cpolar内网穿透隧道推送</h2>
        <table>
            <thead>
                <tr>
                    <th>隧道名称</th>
                    <th>URL</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            <tbody>
    """
    for row in rows:
        cols = row.find_all(['td', 'th'])
        if len(cols) >= 3:  # 适当放宽条件，确保能处理大部分合理情况
            tunnel_name = cols[0].text.strip()
            http_url = cols[1].text.strip() if len(cols) > 1 else ""
            create_time = cols[4].text.strip() if len(cols) > 4 else ""
            
            # 添加到新的HTML中
            new_html += f"""
                <tr>
                    <td data-label="隧道名称">{tunnel_name}</td>
                    <td data-label="URL"><a href="{http_url}" target="_blank">{http_url}</a></td>
                    <td data-label="创建时间">{create_time}</td>
                </tr>
            """
    new_html += """
            </tbody>
        </table>
    </div>
</body>
</html>
"""


# 将新的HTML内容写入文件
#with open('new_online_tunnels.html', 'w', encoding='utf-8') as file:
    #file.write(new_html)

#print("新的HTML文件已创建并保存为 'new_online_tunnels.html'")

print(result)
#print(tunnel_info_list)
title = 'cpolar内网穿透隧道信息'
contents = result 
notify2.send(title,result)
#requests.get(f'https://wxpusher.zjiecode.com/api/send/message/?appToken=AT_ekLBIYnit0xNW09PGXYm36B8NTBWL3o2&content={result}&uid=UID_4nP12Q8xthtkBfMgugmZdCEV8ZpU&url=http%3a%2f%2fwxpusher.zjiecode.com')
wxpusher.send(title,new_html)